package com.baike.controller;


import com.baike.data.Result;
import com.baike.em.ConstantEnum;
import com.baike.entity.TbLesson;
import com.baike.feign.TbLessonFeign;
import com.baike.service.impl.TbLessonServiceImpl;
import com.baike.utils.MyIdWorker;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lbs
 * @since 2021-10-29
 */
@RestController
@RequestMapping("lessonController")
@Api("课程管理实例")
public class TbLessonController {
    @Autowired
    private TbLessonServiceImpl lessonService;
    @Autowired
    private MyIdWorker myIdWorker;
    @Autowired
    private TbLessonFeign lessonFeign;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;//测试暂用


    @PostMapping
    @ApiOperation("接收JSON格式的课程实体类数据用于数据库添加")
    @ApiImplicitParam(value = "课程实体类数据",name = "lesson",required = true,paramType = "body")
    public Result postLess(@RequestBody TbLesson lesson){

        // 判断传来的实体类是否包含一些数据
        if(Objects.isNull(lesson.getLessonTeacherId())){
            return Result.build(ConstantEnum.NULL_DATA_PARAMETER);
        }


        long l = myIdWorker.nextId();
        // 判断是否传过来Id
        if(Objects.isNull(lesson.getLessonId())){
            lesson.setLessonId(l);
        }
        boolean b = lessonService.save(lesson);

        //根据增加结果返回状态码
        if(b){
            // 增加关联表信息
            if(StringUtils.isNotEmpty(lesson.getLessonLabelIds())){
                Result<ConstantEnum> result = lessonFeign.putLessonLabel(l, lesson.getLessonLabelIds());
                // 设置修改关联表信息成功与否
                String message = "";
                if(result.getCode().equals(2000)){
                    message = "修改关联表成功";
                }else {
                    message = "修改关联表失败";
                }
                return Result.build(ConstantEnum.SUCCESS).setResult(message);
            }
            return Result.build(ConstantEnum.NULL_DATA).setResult("关联数据传输错误");

        }

       return Result.build(ConstantEnum.ERROR);
    }

    @DeleteMapping
    @ApiOperation("根据id集合删除课程状态")
    @ApiImplicitParam(value = "课程id集合",name = "ids",required = true,paramType = "query")
    public Result delLess(@RequestParam("ids")Long[] ids){
        UpdateWrapper<TbLesson> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("lesson_id",Arrays.asList(ids)).set("lesson_delete",1);
        boolean b = lessonService.update(updateWrapper);
        //根据删除结果返回状态码
        if(b){
            Result<ConstantEnum> result = lessonFeign.delLessonLabelByLessonId(ids);

            //设置删除关联表返回信息
            String message = "";
            if (result.getCode().equals(2000)){
                message = "删除关联表成功";
            }else {
                message = "删除关联表失败";
            }
            return Result.build(ConstantEnum.SUCCESS).setResult(message);
        }
        return Result.build(ConstantEnum.ERROR);
    }

    @PutMapping
    @ApiOperation("根据id修改课程数据")
    @ApiImplicitParam(value = "课程修改数据",name = "lesson",required = true,paramType = "body")
    public Result<ConstantEnum> putLesson(@RequestBody TbLesson lesson){
        boolean b = lessonService.updateById(lesson);
        //根据修改结果返回状态码
        if(b){
            // 判断是否改动标签信息
            // 设置删除关联表信息成功与否
            String message = "";
            if(lesson.getLessonLabelIds() != null && !"".equals(lesson.getLessonLabelIds())){
                // 增加关联表信息
                Result<ConstantEnum> result = lessonFeign.putLessonLabel(lesson.getLessonId(), lesson.getLessonLabelIds());

                if(result.getCode().equals(2000)){
                    message = "删除关联表成功";
                }else {
                    message = "删除关联表失败";
                }
            }


            return Result.build(ConstantEnum.SUCCESS).setResult(message);
        }
        return Result.build(ConstantEnum.ERROR);
    }

    @PostMapping("findByWrapper")
    @ApiOperation("根据输入的条件对课程筛选")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页数",name = "pageNumber",required = false,paramType = "query"),
            @ApiImplicitParam(value = "每页条数",name = "pageSize",required = false,paramType = "query"),
            @ApiImplicitParam(value = "课程名称关键字",name = "lessonName",required = false,paramType = "query"),
            @ApiImplicitParam(value = "一级分类",name = "Categories1",required = false,paramType = "query"),
            @ApiImplicitParam(value = "二级分类",name = "Categories2",required = false,paramType = "query"),
            @ApiImplicitParam(value = "上线时间大于参数",name = "maxTime",required = false,paramType = "query"),
            @ApiImplicitParam(value = "上线时间小于参数",name = "minTime",required = false,paramType = "query"),
            @ApiImplicitParam(value = "金额大于课程单价",name = "maxPrice",required = false,paramType = "query"),
            @ApiImplicitParam(value = "金额小于课程单价",name = "minPrice",required = false,paramType = "query"),
            @ApiImplicitParam(value = "审核状态 0待审核 1审核通过 2审核未通过 3 下架",name = "status",required = false,paramType = "query"),
            @ApiImplicitParam(value = "删除状态 0 未删除 1已删除",name = "delStatus",required = false,paramType = "query"),
            @ApiImplicitParam(value = "是否收费 0收费 1免费",name = "lessonFree",required = false,paramType = "query"),
            @ApiImplicitParam(value = "销量降序 ",name = "desc",required = false,paramType = "query"),
            @ApiImplicitParam(value = "销量升序",name = "asc",required = false,paramType = "query"),
            @ApiImplicitParam(value = "教师id",name = "teacherId",required = false,paramType = "query"),
            @ApiImplicitParam(value = "课程id数组",name = "ids",required = false,paramType = "query"),
    })
    public Result<TbLesson> findByWrapper(@RequestParam(value = "pageNumber",defaultValue = "0",required = false)Integer pageNumber,
                                          @RequestParam(value = "pageSize",defaultValue = "10",required = false)Integer pageSize,
                                          @RequestParam(value = "lessonName",required = false)String lessonName,
                                          @RequestParam(value = "Categories1",required = false)Integer Categories1,
                                          @RequestParam(value = "Categories2",required = false)Integer Categories2,
                                          @RequestParam(value = "maxTime",required = false)String maxTime,
                                          @RequestParam(value = "minTime",required = false)String minTime,
                                          @RequestParam(value = "maxPrice",required = false)Double maxPrice,
                                          @RequestParam(value = "minPrice",required = false)Double minPrice,
                                          @RequestParam(value = "status",required = false) Integer status,
                                          @RequestParam(value = "delStatus",required = false) Integer delStatus,
                                          @RequestParam(value = "lessonFree",required = false) Integer lessonFree,
                                          @RequestParam(value = "desc",required = false) Integer desc,
                                          @RequestParam(value = "asc",required = false) Integer asc,
                                          @RequestParam(value = "teacherId",required = false) Integer teacherId,
                                          @RequestParam(value = "ids",required = false)Long[] ids
                                          ){
        Page<TbLesson> page = new Page<>(pageNumber,pageSize); // 如果不要总记录时 在这里写个 false

        LambdaQueryWrapper<TbLesson> wrapper = Wrappers.<TbLesson>lambdaQuery().like(StringUtils.isNotEmpty(lessonName), TbLesson::getLessonName, lessonName)
                .eq(Objects.nonNull(Categories1), TbLesson::getLessonCategories1, Categories1)
                .eq(Objects.nonNull(Categories2), TbLesson::getLessonCategories2, Categories2)
                .gt(Objects.nonNull(maxTime), TbLesson::getLessonPublishDate, maxTime)
                .lt(Objects.nonNull(minTime), TbLesson::getLessonPublishDate, minTime)
                .gt(Objects.nonNull(maxPrice), TbLesson::getLessonPrice, maxPrice)
                .gt(Objects.nonNull(minPrice), TbLesson::getLessonPrice, minPrice)
                .eq(Objects.nonNull(status), TbLesson::getLessonStatus, status)
                .eq(Objects.nonNull(delStatus), TbLesson::getLessonDelete, delStatus)
                .eq(Objects.nonNull(lessonFree), TbLesson::getLessonFree, lessonFree)
                .eq(Objects.nonNull(teacherId), TbLesson::getLessonTeacherId, teacherId)
                .orderByDesc(Objects.nonNull(desc), TbLesson::getLessonCount)
                .orderByAsc(Objects.nonNull(asc), TbLesson::getLessonCount);
        if(Objects.nonNull(ids)){
            wrapper.in(Objects.nonNull(ids), TbLesson::getLessonId,Arrays.asList(ids));
        }
        IPage<TbLesson> lessonIPage = lessonService.page(page, wrapper);
        List<TbLesson> lessonList = lessonIPage.getRecords();
        if(lessonList.size() > 0){
            return Result.build(ConstantEnum.SUCCESS).setResult(lessonList);
        }
        return Result.build(ConstantEnum.NULL_DATA);
    }





    //根据课程id回显信息
    @ApiOperation(value = "课程信息回显接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lessonId",value = "课程id",required = true,paramType = "path")
    })
    @GetMapping("/selectByLessonId/{lessonId}")
    public Result selectByLessonId(@PathVariable("lessonId")Long lessonId){
        TbLesson tbLesson = lessonService.getById(lessonId);
        return Result.build(ConstantEnum.SUCCESS).setResult(tbLesson);

    }

    @ApiOperation(value = "根据课程id审核 进行审核 0 待审核 1通过 2 驳回 3关闭")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lessonId",value = "课程id",required = true,paramType = "query"),
            @ApiImplicitParam(name = "lessonStatus",value = "审核状态",required = true,paramType = "query"),
    })
    @PutMapping("updateStatusByLessonId")
    public Result updateStatus(@RequestParam("lessonId") Long lessonId,
                               @RequestParam("lessonStatus")Integer lessonStatus){
        TbLesson lesson = lessonService.getById(lessonId);
        //修改课程的状态,审核通过后通过mq把课程的id发送出去
        UpdateWrapper<TbLesson> updateWrapper = new UpdateWrapper();
        updateWrapper.set("lesson_status",lessonStatus);
        boolean b = lessonService.update(updateWrapper);
        if(b){
            rocketMQTemplate.convertAndSend("lessons_Topic",lessonId);  //生产者发送消息
            return Result.build(ConstantEnum.SUCCESS).setResult("页面生成成功");
        }else {
            return Result.build(ConstantEnum.ERROR).setResult("修改失败，无法生成静态页面");
        }


    }

}
